#!/bin/sh
killall -q dnsmasq
pppoa_ifname="atm0" # hack for ppp over atm, which has no ${proto}_ifname
args2=""

#
# initialize any missing nvram variables and turn on dhcp
#   for LAN by default.
#
if [ -z $(nvram get lan_dhcp_enabled) ]; then
	nvram set lan_dhcp_enabled=1					
fi	
for ifname in lan wan wifi $(nvram get ifnames); do			
	if [ -z $(nvram get ${ifname}_dhcp_start) ]; then
		# cut is in case someone set a full IP here instead of integer
		nvram set ${ifname}_dhcp_start=$(nvram get dhcp_start | cut -d '.' -f 4)
	fi
	if [ -z $(nvram get ${ifname}_dhcp_num) ]; then
		nvram set ${ifname}_dhcp_num=$(nvram get dhcp_num)
	fi
	if [ -z $(nvram get ${ifname}_dhcp_lease) ]; then
		nvram set ${ifname}_dhcp_lease=$(nvram get dhcp_lease)				
	fi
done	

for ifname in lan wan wifi $(nvram get ifnames); do
    dhcp_enabled=$(nvram get ${ifname}_dhcp_enabled)
    if [ "$dhcp_enabled" = 1 ]; then
        dnsmasq_enabled=1
        
        IFPROTO=$(nvram get ${ifname}_proto)
        IFACE=$(nvram get ${ifname}_ifname)
        IFACES=$(nvram get ${ifname}_ifnames)
        
        ipaddr=$(nvram get ${ifname}_ipaddr)
        netmask=$(nvram get ${ifname}_netmask)
        
        start=$(nvram get ${ifname}_dhcp_start)
        num=$(nvram get ${ifname}_dhcp_num)	
        if [ -f "/bin/ipcalc.sh" ]; then
        	eval $(ipcalc.sh $ipaddr $netmask ${start:-100} ${num:-150})
        else
        	eval $(ipcalc $ipaddr $netmask ${start:-100} ${num:-150})
        fi
        lease=$(nvram get ${ifname}_dhcp_lease)
	[ "$lease" = "0" ] && {
		lease="12h"
		nvram set "${ifname}_dhcp_lease=12h"
	}
        args2="$args2 -F $ifname,$START,$END,$NETMASK,${lease:-12h}"
    fi
done

if [ "$dnsmasq_enabled" = 1 ]; then   
        cache_size=$(nvram get dhcp_cache_size) #-c
        no_hosts=$(nvram get dhcp_no_hosts) #-h
        no_regcache=$(nvram get dhcp_no_regcache) #-N
        strict_order=$(nvram get dhcp_strict_order) #-o
        port=$(nvram get dhcp_port) #-p
        log_queries=$(nvram get dhcp_log_queries) #-q
        no_resolv=$(nvram get dhcp_no_resolv) #-R
        domain=$(nvram get dhcp_domain) #-s
        dhcp_lease_max=$(nvram get dhcp_lease_max) #-X
        read_ethers=$(nvram get dhcp_read_ethers) #-Z
        
        args="-l /tmp/dhcp.leases -K $args2" # ${wanif:+-I ${wanif}}"
        args="$args ${cache_size:+-c ${cache_size}} ${port:+-p ${port}} ${dhcp_lease_max:+-X ${dhcp_lease_max}}"
        args="$args ${domain:+-s ${domain}} ${read_ethers:+-Z } ${no_resolv:+-R} ${log_queries:+-q} ${strict_order:+-o} ${no_regcache:+-N}"
        args="$args ${no_hosts:+-h}"
        dnsmasq ${args}    
fi
